package restaurant.behaviours.booking;

import jade.core.behaviours.CyclicBehaviour;
import jade.lang.acl.ACLMessage;
import jade.lang.acl.MessageTemplate;
import restaurant.agents.BookingAgent;
import restaurant.core.CustomizedPerformative;
import restaurant.core.Table;

/**
 * BookingAgent behaviour which performs the action to book a table
 * @author Domenico Ventura
 *
 */
public class BookingConfirmBehaviour extends CyclicBehaviour {

	private static final long serialVersionUID = 4100757982613260359L;
	private BookingAgent agent;
	
	public BookingConfirmBehaviour(BookingAgent agent) {
		super(agent);
		this.agent = agent;
	}
	
	@Override
	public void action() {
		MessageTemplate messageTemplate = MessageTemplate.MatchPerformative(CustomizedPerformative.ACCEPT_TABLE);
		ACLMessage message = myAgent.receive(messageTemplate);
		if(message != null) {
			String table = message.getContent().split(" ")[1];
			ACLMessage answer = message.createReply();
			
			System.out.println("BookingAgent: " + message.getSender().getLocalName() + " conferma il tavolo n. " + table);
			
			/*
			 * if the table requested from customer is free then this behaviour books it
			 * else it will answer "not-available"
			 */
			Table t = this.agent.restaurant.tables.get(Integer.parseInt(table));
			if(t != null && t.isFree()) {
				t.setCustomer(message.getSender());
				t.setFree(false);
				t.setCustomerType(message.getContent().split(" ")[3]);
				
				answer.setContent("OK");
				this.agent.setScore(this.agent.getScore() + 1);
				System.out.println("BookingAgent: Tavolo n. " + table + " prenotato dal cliente " + message.getSender().getLocalName());
			} else {
				this.agent.setScore(this.agent.getScore() - 1);
				answer.setContent("not-available");
				
				System.out.println("BookingAgent: Impossibile prenotare il tavolo");
			}
			myAgent.send(answer);
		}
	}
}